import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaExecuteJS {
    public static void main(String[] args) {
        // 创建JavaScript引擎
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        try {
            // 定义JavaScript函数
            String script =
                    "function add(a, b, c) {" +
                            "    return a + b + c;" +
                            "};" +
                            "function concatStrings(str1, str2, str3) {" +
                            "    return str1 + ' ' + str2 + ' ' + str3;" +
                            "};" +
                            "function complexOperation(num, str, bool) {" +
                            "    return 'Result: ' + (num * 2) + ', ' + str.toUpperCase() + ', ' + !bool;" +
                            "};";

            // 执行脚本以定义函数
            engine.eval(script);

            // 方式一：直接在eval中调用函数并传递参数
            Object result1 = engine.eval("add(10, 20, 30)");
            System.out.println("加法结果: " + result1);

            Object result2 = engine.eval("concatStrings('Hello', 'from', 'Java')");
            System.out.println("字符串连接结果: " + result2);

            // 方式二：通过bindings传递参数
            engine.put("x", 5);
            engine.put("y", 10);
            engine.put("z", 15);
            Object result3 = engine.eval("add(x, y, z)");
            System.out.println("通过bindings传递参数的加法结果: " + result3);

            // 传递不同类型的参数
            engine.put("numParam", 7);
            engine.put("strParam", "javascript");
            engine.put("boolParam", true);
            Object result4 = engine.eval("complexOperation(numParam, strParam, boolParam)");
            System.out.println("复杂操作结果: " + result4);

        } catch (ScriptException e) {
            System.err.println("执行JavaScript脚本时出错: " + e.getMessage());
        }
    }
}